<template>
  <div>
    <Modal
      class="add_form"
      v-model="visible"
      :title="`${mcpId ? '编辑' : '创建'}MCP服务`"
      :mask-closable="false"
      draggable
      sticky
      scrollable
      @on-cancel="cancel"
      width="800px"
    >
      <Form ref="formEl" :model="formData" :rules="rules" label-position="top">
        <FormItem label="名称" prop="name">
          <Input
            v-model="formData.name"
            placeholder="请输入名称"
            clearable
          ></Input>
        </FormItem>
        <div class="flex_form_item">
          <p>暴露的应用</p>
          <Button @click="handleSelectShow">管理</Button>
        </div>
        <el-table :data="formData.mcpBodyList" style="width: 100%">
        <el-table-column label="工具名" prop="toolname" min-width="200px">
          <template #default="{ row }">
              <Input
                v-model="row.toolname"
                placeholder="建议使用英文名"
                size="small"
              ></Input>
          </template>
        </el-table-column>
        <el-table-column label="应用名" prop="appname">
        </el-table-column>
        <el-table-column label="应用描述" prop="appdesc" min-width="200px">
          <template #default="{ row }">
            <Input
              v-model="row.appdesc"
              size="small"
              placeholder="应用描述"
              show-word-limit
              maxlength="50"
            ></Input>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <Icon
              class="cursor-pointer"
              size="20"
              type="ios-trash"
              @click="handleTableRemove(scope.$index)"
            ></Icon>
          </template>
        </el-table-column>
      </el-table>
      </Form>
      <template #footer>
        <Button @click="cancel">取消</Button>
        <Button type="primary" :loading="loading" @click="submit">确定</Button>
      </template>
    </Modal>
    <Modal
      v-model="showAppSelect"
      title="应用选择"
      :mask-closable="false"
      draggable
      width="800px"
      @on-ok="handleSelectConfirm"
    >
      <div class="select-box">
        <div class="left">
          <Input v-model="searchText" prefix="ios-search" placeholder="搜索应用" style="width: 100%" />
          <CheckboxGroup v-model="selectList" class="select-list">
              <Checkbox :label="item.id" v-for="item in filterAgentFlowList" :key="item.id" class="select-item">
                {{ item.name }}
              </Checkbox>
          </CheckboxGroup>
        </div>
        <div class="right">
          <p class="right-header">已选择： {{ selectList.length }}</p>
          <div class="select-list">
            <div class="flex-item" v-for="item in filterSelectList" :key="item.id">
              <p>{{ item.name }}</p>
              <Icon type="md-close" size="18" style="cursor: pointer;" @click="handleSelectRemove(item.id)" />
            </div>
          </div>
        </div>
      </div>
  </Modal>
  </div>
</template>
<script setup>
import { ref, computed } from 'vue';
import { Message } from 'view-ui-plus';

import { createMCP, updateMCP, detailMCP, listAgentflow } from '@/api/modules/mcp';

const emit = defineEmits(['submit'])
const visible = ref(false);
const showAppSelect = ref(false);
const mcpId = ref(undefined);
// 加载
const loading = ref(false);
// 应用选择
const searchText = ref('');
const selectList = ref([]);
const agentFlowList = ref([]);
// 表单元素ref
const formEl = ref(null);

// 表单字段
const formData = ref({
  name: '',
  mcpBodyList: [],
});

// 回显已选择的数据
const filterSelectList = computed(() => {
  return agentFlowList.value.filter(item => {
    const index = selectList.value.findIndex(j => j == item.id);
    return index >= 0;
  })
});
// 筛选列表数据
const filterAgentFlowList = computed(() => {
  return agentFlowList.value.filter(item => item.name.indexOf(searchText.value) > -1)
});
const handleSelectShow = () => {
  if (mcpId.value) {
    selectList.value = formData.value.mcpBodyList.map(item => item.serviceaiid)
  }
  showAppSelect.value = true
}
const handleSelectRemove = id => {
  const index = selectList.value.findIndex(i => i == id);
  selectList.value.splice(index, 1);
}
const handleSelectConfirm = () => {
  formData.value.mcpBodyList = filterSelectList.value.map(item => {
    return {
      serviceaiid: item.id,
      toolname: item.name,
      appname: item.name,
      appdesc: '',
    }
  });
}
// 表单校验条件
const rules = ref({
  name: [{ required: true, message: '请填写名称', trigger: 'blur' }],
});
const initDialog = async (id) => {
  
  mcpId.value = id;
  if (id) {
    const { data } = await detailMCP({data:{id}})
    formData.value.mcpBodyList = data.mcpBodyList.map(item => {
      return {
        serviceaiid: item.serviceaiid,
        toolname: item.toolname,
        appname: item.appname,
        appdesc: item.appdesc,
        id: item.id,
        mcpheadid:item.mcpheadid,
      }
    });
    formData.value.name = data.name;
  }
  visible.value = true;
};

const handleTableRemove = (index) => {
  formData.value.mcpBodyList.splice(index, 1);
};
const getAgentFlowList = async() => {
  const { data } = await listAgentflow()
  agentFlowList.value = data;
}
getAgentFlowList()
/**
* 提交表单
*/
const submit = async () => {
  let valid = await formEl.value.validate((valid, fild) => valid ? valid : fild);
  if (!valid) return;
  for(let item of formData.value.mcpBodyList){
    if(!item.toolname){
      Message.error('请填写工具名')
      return;
    }
  }
  loading.value = true;
  try {
    await (mcpId.value ? updateMCP : createMCP)({data: {...formData.value, id: mcpId.value || undefined }});
    Message.success('提交成功')
    loading.value = false;
    visible.value = false;
    searchText.value = '';
    selectList.value = [];
    formEl.value.resetFields();
    formData.value.mcpBodyList = [];
    emit('submit')
  }catch (error) {
    console.log(error)
  }
}

const cancel = () => {
  visible.value = false;
  selectList.value = [];
  formEl.value.resetFields();
  formData.value.mcpBodyList = [];
  searchText.value = '';
}

defineExpose({
  initDialog,
});
</script>
<style lang="scss" scoped>
.select-box {
  width: 100%;
  height: 400px;
  border: 1px solid #eee;
  border-radius: 8px;
  display: flex;
  overflow: hidden;
  .left {
    flex-basis: 50%;
    height: 100%;
    padding: 10px;
    border-right: 1px solid #eee;
    overflow: hidden;
  }
  .select-list {
    height: calc(100% - 30px);
    overflow-y: auto;
    overflow-x: hidden;
    padding-top: 10px;
    padding-right: 4px;
  }
  .select-item {
    width: 100%;
    margin: 5px 0;
    width: 100%;
    font-size: 15px;
    text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;
  }
  .flex-item {
    width: 100%;
    display: inline-flex;
    align-items: center;
    justify-content: space-between;
    margin: 6px 0;
    width: 100%;
    p {
      flex: 1;
      font-size: 15px;
      text-overflow: ellipsis;
      overflow: hidden;
      white-space: nowrap;
    }
  }
  .right {
    flex-basis: 50%;
    padding: 10px;
    overflow: hidden;
    &-header {
      padding-top: 10px;
      font-size: 14px;
      color: #333;
    }
  }
}
</style>